package com.alibaba.citrus.cr.price.ability.facade;

import com.alibaba.acm.shaded.com.google.common.collect.Lists;
import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.price.ability.functions.PlatformCodeFlagEnum;
import com.alibaba.citrus.cr.price.ability.functions.constant.ActivityOrderTagEnum;
import com.alibaba.citrus.cr.price.ability.functions.entity.activity.*;
import com.alibaba.citrus.cr.price.ability.functions.factory.activity.*;
import com.alibaba.citrus.cr.price.ability.functions.factory.price.process.PropertyProcessManager;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.api.customerquery.service.CustomerQueryService;
import com.epoch.app.crplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.crplatformenhance.enums.RoleCodeEnum;
import com.epoch.app.crplatformenhance.model.dto.GetLoginEmployOrganizationPermissionsRequest;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.crpricecenter.api.activityquery.dto.QueryPromotionPageListForExportRequest;
import com.epoch.app.crpricecenter.api.activityquery.dto.QueryPromotionPageListRequest;
import com.epoch.app.crpricecenter.api.activityquery.service.ActivityQueryService;
import com.epoch.app.crpricecenter.dto.request.*;
import com.epoch.app.crpricecenter.dto.response.*;
import com.epoch.app.crpricecenter.enums.DimensionPropertyEnum;
import com.epoch.app.crpricecenter.model.dto.*;
import com.epoch.app.crpricecenter.model.enums.ActivityTypeEnum;
import com.epoch.app.crpricecenter.sdo.ActivityTermSDO;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author hanguo
 * @date 2021/10/16
 * @Description 营销活动查询接口实现层
 */
@Primary
@Service
public class ActivityQueryServiceImpl implements ActivityQueryService {
    private static Log log = Log.getLogger(ActivityQueryServiceImpl.class);


    @Resource
    private CustomerQueryService customerQueryService;

    @Resource
    private PropertyProcessManager propertyProcessManager;

    /**
     * 基线能力
     */
    @Resource
    private BaseDataService baseDataService;

    @Autowired
    private ApplicationContext applicationContext;

    @Resource
    private CrPlatformEnhanceService crPlatformEnhanceService;

    @Autowired
    private BcOrderService bcOrderService;
    private final static ArrayList<String> replenishList = Lists.newArrayList(ActivityTypeEnum.REPLENISH_LIST.getValue().split(","));

    @Override
    @FacadeInvoker(value = "查询营销活动列表", errorCode = "OTS-08-001-01-16-024")
    public Result<List<ActivityViewResponse>> queryPromotionPageList(QueryPromotionPageListRequest request) {
        // 控制角色
        EmployeeGetCurrentLoginResponse currentLoginEmployeeRoles = bcOrderService.employeeGetCurrentLogin();
        if (currentLoginEmployeeRoles != null && StringUtils.isNotBlank(currentLoginEmployeeRoles.getRoleCodes())){
            String roleCodes = currentLoginEmployeeRoles.getRoleCodes();
            if (StringUtils.isBlank(roleCodes) || "[]".equals(roleCodes)){
                return Result.success(new ArrayList<>());
            }
            List<String> noPermissionRoleCodeList = Lists.newArrayList(RoleCodeEnum.SALE_MAN.getCode(), RoleCodeEnum.DEPARTMENT_MANAGER.getCode());
            String newRoleCodes = roleCodes.replaceAll(" ", "");
            List<String> roles = Lists.newArrayList(newRoleCodes.substring(1, newRoleCodes.length() - 2).split(","));
            boolean permission = false;
            for (String role : roles) {
                if (!noPermissionRoleCodeList.contains(role)) {
                    permission = true;
                    break;
                }
            }
            if (!permission){
                return Result.success(new ArrayList<>());
            }
        }

        //权限控制
        authorityDetail(request);
        //工厂方式获取entity
        ActivityTermIndexEntity activityTermIndexEntity = ActivityTermIndexFactory.create(request);
        //查询数据
        Result<List<ActivityViewResponse>> result = activityTermIndexEntity.queryPromotionPageList();
        if (CollectionUtils.isEmpty(result.getResult())) {
            return Result.success(new ArrayList<>());
        }
        List<ActivityViewResponse> originResult = result.getResult();
        Map<String, Map<String, String>> propertyMap = obtainPropertyMap(originResult);
        result.setResult(conversionCode2Desc(originResult, propertyMap));
        return result;
    }

    public void authorityDetail(QueryPromotionPageListRequest request){
        GetLoginEmployOrganizationPermissionsRequest currentEmployeeOrganizationRequest = new GetLoginEmployOrganizationPermissionsRequest();
        currentEmployeeOrganizationRequest.setType(OrganizationTypeEnum.SALES_ORGANIZATION.getCode());
        Result<List<com.epoch.app.crplatformenhance.sdo.OrganizationSDO>> loginEmployeeSaleOrganization = crPlatformEnhanceService.getLoginEmployOrganizationPermissions(currentEmployeeOrganizationRequest);
        if (Objects.nonNull(loginEmployeeSaleOrganization) && CollectionUtils.isNotEmpty(loginEmployeeSaleOrganization.getResult())) {
            List<com.epoch.app.crplatformenhance.sdo.OrganizationSDO> organizationSDOList = loginEmployeeSaleOrganization.getResult();
            List<String> salesOrganizationList = organizationSDOList.stream().filter(e->StringUtils.isNotBlank(e.getId())).
                    distinct().map(e->e.getId()).collect(Collectors.toList());
            //获取销售组织外部编码
            List<String> salesOrganizationOutCodeList = Lists.newArrayList();
            Map<String, String> salesOrganizationMap = propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.ORG_SALES_ORGANIZATION_CODE.getKey())
                    .obtainInnerCodeAndOuterCodeMap(salesOrganizationList, true);
            salesOrganizationList.forEach(e -> salesOrganizationOutCodeList.add(salesOrganizationMap.get(e)));
            if (StringUtils.isNotBlank(request.getSalesOrganizationIdSelect())) {
                if (CollectionUtils.isNotEmpty(salesOrganizationOutCodeList) && salesOrganizationOutCodeList.contains(request.getSalesOrganizationIdSelect())) {
                    request.setSalesOrganizationId(Lists.newArrayList(request.getSalesOrganizationIdSelect()));
                }
            } else {
                request.setSalesOrganizationId(salesOrganizationOutCodeList);
            }
        }

        }


    public Map<String, Map<String, String>> obtainPropertyMap(List<ActivityViewResponse> originResult) {

        Map<String, Map<String, String>> propertyMap = Maps.newHashMap();

        //获取所有销售组织的编码list
        List<String> salesOrganizationCodeList = originResult.stream().
                map(ActivityViewResponse::getSalesOrganizationDesc).distinct().collect(Collectors.toList());
        //获取所有销售组织外部编码和desc的映射关系
        Map<String, String> salesOrganizationMap = propertyProcessManager.getPropertyProcess(
                        DimensionPropertyEnum.ORG_SALES_ORGANIZATION_CODE.getKey())
                .obtainCodeAndDescMap(salesOrganizationCodeList, false);
        propertyMap.put(DimensionPropertyEnum.ORG_SALES_ORGANIZATION_CODE.getKey(), salesOrganizationMap);


        //获取所有销售渠道编码
        List<String> channelCoeList = originResult.stream().
                map(ActivityViewResponse::getChannelDesc).distinct().collect(Collectors.toList());
        //获取所有业务渠道外部编码和desc的映射关系
        Map<String, String> channelInnerAndOuterCodeMap = propertyProcessManager.getPropertyProcess(
                DimensionPropertyEnum.CHANNEL_CODE.getKey()).obtainCodeAndDescMap(channelCoeList, false);
        propertyMap.put(DimensionPropertyEnum.CHANNEL_CODE.getKey(), channelInnerAndOuterCodeMap);

        //获取货品单位和描述
        List<String> unitDescList = originResult.stream().
                map(ActivityViewResponse::getUnitDesc).distinct().collect(Collectors.toList());
        Map<String, String> salesUnitMap = propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.SALES_UNIT_CODE.getKey()).obtainCodeAndDescMap(unitDescList, false);
        propertyMap.put(DimensionPropertyEnum.SALES_UNIT_CODE.getKey(), salesUnitMap);

        return propertyMap;
    }

    public List<ActivityViewResponse> conversionCode2Desc(List<ActivityViewResponse> originResult, Map<String, Map<String, String>> propertyMap) {


        //获取活动和客户、货品的对应关系
        Map<String, Map<String, List<String>>> relationMap = obtainActivityRelation(originResult);
        Map<String, List<String>> clientRelationMap = relationMap.get("CLIENT");
        Map<String, List<String>> itemRelationMap = relationMap.get("ITEM");
        Map<String, List<String>> giftRelationMap = relationMap.get("GIFT");

        //获取编码和描述的对应关系
        Map<String, Map<String, String>> pageLinkDescMap = obtainPageLinkDesc(relationMap);
        Map<String, String> clientDescMap = pageLinkDescMap.get("CLIENT");
        Map<String, String> goodsDescMap = pageLinkDescMap.get("GOODS");

//        Integer onlyData = 1;
        return originResult.stream().map(e -> {
            e.setSalesOrganizationDesc(propertyMap.get(
                    DimensionPropertyEnum.ORG_SALES_ORGANIZATION_CODE.getKey()).get(e.getSalesOrganizationDesc()));

            List<String> clientList = clientRelationMap.get(e.getActivityId());
            e.setClientDesc(obtainDetailData(clientList,clientDescMap,true));
            e.setChannelDesc(propertyMap.get(
                    DimensionPropertyEnum.CHANNEL_CODE.getKey()).get(e.getChannelDesc()));

            Optional<ActivityTypeEnum> of = Optional.ofNullable(ActivityTypeEnum.of(e.getActivityTypeDesc()));
            e.setActivityTypeDesc(null);
            if (of.isPresent()) {
                of.ifPresent(o -> e.setActivityTypeDesc(o.getLabel()));
            }

            List<String> itemList = itemRelationMap.get(e.getActivityId() + "_" + e.getActivityTermId());
            e.setItemDesc(obtainDetailData(itemList,goodsDescMap,false));
            List<String> giftList = giftRelationMap.get(e.getActivityId() + "_" + e.getActivityTermId());
            e.setGiftDesc(obtainDetailData(giftList,goodsDescMap,false));
            if(ActivityTypeEnum.SPECIAL_OFFER_PRICE.getLabel().equals(e.getActivityTypeDesc())){
                e.setGiftDesc("特价活动无赠品");
            }
//            ArrayList<String> replenishList = Lists.newArrayList(ActivityTypeEnum.REPLENISH_LIST.getValue().split(","));
//            if(ActivityTypeEnum.REPLENISHMENT.getLabel().equals(e.getActivityTypeDesc())){
//                e.setGiftDesc("补货活动无赠品");
//            }
            if(replenishList.contains(e.getActivityTypeDesc())){
                e.setGiftDesc("补货活动无赠品");
            }


            e.setUnitDesc(propertyMap.get(
                    DimensionPropertyEnum.SALES_UNIT_CODE.getKey()).get(e.getUnitDesc()));


            //新的逻辑，状态以表为准
            //买赠活动如果客户/货品/赠品都没有则该活动不可用
//            if (ActivityTypeEnum.TAKE_GIFT.getLabel().equals(e.getActivityTypeDesc()) && (
//                    StringUtils.isBlank(e.getClientDesc()) ||
//                            StringUtils.isBlank(e.getItemDesc()) ||
//                            StringUtils.isBlank(e.getGiftDesc()))) {
//                e.setActivityStatus(CommStatusEnum.DISABLE.getCode().toString());
//            }
//            //特价活动如果客户/货品/赠品都没有则该活动不可用
//            if ((ActivityTypeEnum.SPECIAL_OFFER_PRICE.getLabel().equals(e.getActivityTypeDesc()) &&
//                    (StringUtils.isBlank(e.getClientDesc()) || StringUtils.isBlank(e.getItemDesc()))
//            )) {
//                e.setActivityStatus(CommStatusEnum.DISABLE.getCode().toString());
//            }
//            //补货活动如果客户没有则该活动不可用
//            if (ActivityTypeEnum.REPLENISHMENT.getLabel().equals(e.getActivityTypeDesc()) &&
//                    (StringUtils.isBlank(e.getClientDesc()))
//            ) {
//                e.setActivityStatus(CommStatusEnum.DISABLE.getCode().toString());
//            }

            return e;
        }).collect(Collectors.toList());
    }


    //客户，原品，赠品显示的处理
    public String obtainDetailData(List<String> codeList, Map<String, String> codeAndDescMap,Boolean clientFlag){
        Integer onlyData = 1;
        ////之前的逻辑，只有一条数据时显示，否则不显示
        ////现在的逻辑，有数据时显示明细，否则不显示
        //最新的逻辑,客户只有一条数据时显示，多条则显示明细,不要怀疑这个逻辑，是产品说要这么干的
        ////最最最新的逻辑，回到了最初的起点，一条的时候展示信息，多条显示明细，产品又变卦了！！！

        if (true) {
            //有一条时显示,否则展示明细信息
            if (CollectionUtils.isEmpty(codeList)) {
                return "";
            }
            Integer count = 0;
            String codeFlag = null;
            for (String code : codeList) {
                String desc = codeAndDescMap.get(code);
                if (StringUtils.isNotBlank(desc)) {
                    count++;
                    codeFlag = code;
                }
            }
            if (count.equals(onlyData)) {
                return codeAndDescMap.get(codeFlag);
            } else if (count > onlyData) {
                return "查看明细";
            } else {
                return "";
            }
        } else {
            if (CollectionUtils.isEmpty(codeList)) {
                return "";
            }
            int count = 0;
            for (String code : codeList) {
                String desc = codeAndDescMap.get(code);
                if (StringUtils.isNotBlank(desc)) {
                    count++;
                    break;
                }
            }
            if (count > 0) {
                return "查看明细";
            }
            return "";
        }

    }


    //获取活动下对应的客户/原品/赠品数据
    public Map<String,Map<String,List<String>>> obtainActivityRelation(List<ActivityViewResponse> responses){
        Map<String,Map<String,List<String>>> map = new HashMap<>();

        List<String> activityIds = responses.stream().map(ActivityViewResponse::getActivityId).collect(Collectors.toList());

        ActivityTitleEntity activityTitleEntity = ActivityTitleFactory.create(new ArrayList<>());
        //获取activity_id和clientIds的对应关系
        Map<String,List<String>> activityAndClientMap = activityTitleEntity.queryActivityAndCustomerMap(activityIds);
        map.put("CLIENT",activityAndClientMap);

        //获取活动id和活动项目id的对应关系
        Map<String, String> activityMap = responses.stream().collect(Collectors.toMap(ActivityViewResponse::getActivityTermId,
                ActivityViewResponse::getActivityId, (x, y) -> x));

        //获取activity_id+"_"+activity_term_id和itemIds的对应关系
        ActivityTermEntity activityTermEntity = ActivityTermFactory.create(new ActivityTermSDO());
        Map<String,List<String>> itemMap = activityTermEntity.queryActivityAndItermMap(activityMap);
        map.put("ITEM",itemMap);

        //获取activity_id+"_"+activity_term_id和giftIds的对应关系
        Map<String,List<String>> giftMap = activityTermEntity.queryActivityAndGiftMap(activityMap);
        map.put("GIFT",giftMap);
        return map;

    }

    //获取活动下对应的客户/原品/赠品数据 对于导出功能
    public Map<String,Map<String,List<String>>> obtainActivityRelationForExport(List<ActivityViewResponse> responses){
        Map<String,Map<String,List<String>>> map = new HashMap<>();

        List<String> activityIds = responses.stream().map(ActivityViewResponse::getActivityId).collect(Collectors.toList());

        ActivityTitleEntity activityTitleEntity = ActivityTitleFactory.create(new ArrayList<>());
        //获取activity_id和clientIds的对应关系
        Map<String,List<String>> activityAndClientMap = activityTitleEntity.queryActivityAndCustomerMapForExport(activityIds);
        map.put("CLIENT",activityAndClientMap);

        //获取活动id和活动项目id的对应关系
        Map<String, String> activityMap = responses.stream().collect(Collectors.toMap(ActivityViewResponse::getActivityTermId,
                ActivityViewResponse::getActivityId, (x, y) -> x));

        //获取activity_id+"_"+activity_term_id和itemIds的对应关系
        ActivityTermEntity activityTermEntity = ActivityTermFactory.create(new ActivityTermSDO());
        Map<String,List<String>> itemMap = activityTermEntity.queryActivityAndItermMapExport(activityMap);
        map.put("ITEM",itemMap);

        //获取activity_id+"_"+activity_term_id和giftIds的对应关系
        Map<String,List<String>> giftMap = activityTermEntity.queryActivityAndGiftMapExport(activityMap);
        map.put("GIFT",giftMap);
        return map;

    }

    public Map<String,Map<String,String>> obtainPageLinkDesc(Map<String, Map<String, List<String>>> relationMap){
        Map<String,Map<String,String>> map = new HashMap<>();

        Map<String, List<String>> clientRelationMap = relationMap.get("CLIENT");
        Map<String, List<String>> itemRelationMap = relationMap.get("ITEM");
        Map<String, List<String>> giftRelationMap = relationMap.get("GIFT");
        //获取所有的客户编码
        List<String> clientList = Lists.newArrayList();
        for (String e : clientRelationMap.keySet()) {
            clientList.addAll(clientRelationMap.get(e));
        }
        clientList = clientList.stream().filter(StringUtils::isNotEmpty).distinct().collect(Collectors.toList());

        //获取客户信息
        Map<String, String> customerCodeAndDescMap = propertyProcessManager.getPropertyProcess(
                DimensionPropertyEnum.CUSTOM_CODE.getKey()).obtainCodeAndDescMap(clientList, false);
        //获取客户地址信息（送达方）
        Map<String, String> customerAddressCodeAndDescMap = propertyProcessManager.getPropertyProcess(
                DimensionPropertyEnum.CUSTOMER_SEND_ADDRESS_CODE.getKey()).obtainCodeAndDescMap(clientList, false);
        Map<String, String> clientMap = Maps.newHashMap();
        clientMap.putAll(customerAddressCodeAndDescMap);
        clientMap.putAll(customerCodeAndDescMap);
        map.put("CLIENT",clientMap);

        //获取所有的货品编码
        List<String> goodsList = Lists.newArrayList();
        for (String e : itemRelationMap.keySet()) {
            goodsList.addAll(itemRelationMap.get(e));
        }
        for (String e : giftRelationMap.keySet()) {
            goodsList.addAll(giftRelationMap.get(e));
        }
        goodsList = goodsList.stream().filter(StringUtils::isNotEmpty).distinct().collect(Collectors.toList());

        //获取货品信息
        Map<String, String> itemCodeAndDescMap = propertyProcessManager.getPropertyProcess(
                DimensionPropertyEnum.MATERIAL_CODE.getKey()).obtainCodeAndDescMap(goodsList, false);
        map.put("GOODS",itemCodeAndDescMap);
        return map;
    }

    @FacadeInvoker(value = "导出营销活动列表", errorCode = "OTS-08-001-01-16-035")
    @Override
    public Result<List<ActivityViewResponse>> queryPromotionPageListForExport(QueryPromotionPageListForExportRequest queryPromotionPageListForExportRequest) {
        QueryPromotionPageListRequest queryPromotionPageListRequest = new QueryPromotionPageListRequest();
        BeanUtils.copyProperties(queryPromotionPageListForExportRequest, queryPromotionPageListRequest);
        Result<List<ActivityViewResponse>> result = this.queryPromotionPageList(queryPromotionPageListRequest);
        if (Objects.isNull(result) || CollectionUtils.isEmpty(result.getResult())) {
            return Result.success(new ArrayList<>());
        }
        Map<String, Map<String, List<String>>> relation = obtainActivityRelationForExport(result.getResult());
        fillClientAndItem(result.getResult(), relation);
        return result;

    }

    private void fillClientAndItem(List<ActivityViewResponse> result, Map<String, Map<String, List<String>>> relation) {
        //获取所有的客户数据
        Map<String, List<String>> clientRelationMap = relation.get("CLIENT");
        List<String> clientCodeList = Lists.newArrayList();
        for (Map.Entry<String, List<String>> e : clientRelationMap.entrySet()) {
            clientCodeList.addAll(e.getValue());
        }
        clientCodeList = new ArrayList<>(clientCodeList.stream().collect(Collectors.toSet()));

        Map<String, String> clientCodeAndDescMap = Maps.newHashMap();
            //编码和描述的对应关系
            //获取所有的客户信息
            Map<String, String> customerCodeAndDescMap = propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.
                    CUSTOM_CODE.getKey()).obtainCodeAndDescMap(clientCodeList, false);
            //获取所有的送达方信息
            Map<String, String> addressCodeAndDescMap = propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.
                    CUSTOMER_SEND_ADDRESS_CODE.getKey()).obtainCodeAndDescMap(clientCodeList, false);
            clientCodeAndDescMap.putAll(addressCodeAndDescMap);
            clientCodeAndDescMap.putAll(customerCodeAndDescMap);

        //获取所有的货品数据
        List<String> goodsCodeList = Lists.newArrayList();
        Map<String, List<String>> itemAndActivityRelationMap = relation.get("ITEM");
        Map<String, List<String>> giftAndActivityRelationMap = relation.get("GIFT");

        itemAndActivityRelationMap.entrySet().forEach(e -> goodsCodeList.addAll(e.getValue()));
        giftAndActivityRelationMap.entrySet().forEach(e -> goodsCodeList.addAll(e.getValue()));

        List<String> newGoodsCodeList = new ArrayList<>(goodsCodeList.stream().collect(Collectors.toSet()));

        //货品编码和描述的对应关系
        Map<String, String> goodsCodeAndDescMap = Maps.newHashMap();
        Map<String, String> itemCodeAndDescMap = propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.
                MATERIAL_CODE.getKey()).obtainCodeAndDescMap(newGoodsCodeList, false);
        goodsCodeAndDescMap.putAll(itemCodeAndDescMap);


        result.forEach(e->{

            List<String> clientList = clientRelationMap.get(e.getActivityId());
            if(CollectionUtils.isNotEmpty(clientList)){
                StringBuilder clientNameList = new StringBuilder();
                StringBuilder clientCodeStrList = new StringBuilder();
                clientList.forEach(client->{
                    String clientName = clientCodeAndDescMap.get(client);
                    if(StringUtils.isNotBlank(clientName)){
                        clientNameList.append(clientName).append(",");
                        clientCodeStrList.append(client).append(",");

                    }
                });

                e.setClientDesc(clientNameList.toString());
                e.setClientCodeDesc(clientCodeStrList.toString());

            }


            List<String> itemList = itemAndActivityRelationMap.get(e.getActivityId()+"_"+e.getActivityTermId());

            if(CollectionUtils.isNotEmpty(itemList)){
                StringBuilder itemNameList = new StringBuilder();
                StringBuilder itemCodeList = new StringBuilder();
                itemList.forEach(item->{
                    String itemName = goodsCodeAndDescMap.get(item);
                    if(StringUtils.isNotBlank(itemName)){
                        itemNameList.append(itemName).append(",");
                        itemCodeList.append(item).append(",");
                    }
                });
                e.setItemDesc(itemNameList.toString());
                e.setItemCodeDesc(itemCodeList.toString());
            }

            List<String> giftList = giftAndActivityRelationMap.get(e.getActivityId()+"_"+e.getActivityTermId());
            if(CollectionUtils.isNotEmpty(giftList)){
                StringBuilder giftNameList = new StringBuilder();
                StringBuilder giftCodeList = new StringBuilder();
                giftList.forEach(gift->{
                    String giftName = goodsCodeAndDescMap.get(gift);
                    if(StringUtils.isNotBlank(giftName)){
                        giftNameList.append(giftName).append(",");
                        giftCodeList.append(gift).append(",");
                    }
                });
                e.setGiftDesc(giftNameList.toString());
                e.setGiftCodeDesc(giftCodeList.toString());
            }

        });
    }


    @Override
    @FacadeInvoker(value = "查询渠道", errorCode = "OTS-08-001-01-16-025")
    public CommonDropBox queryChannelForDropBox(DropBoxViewRequest dropBoxViewRequest) {
        //工厂方式获取entity
        ActivityTermIndexEntity activityTermIndexEntity = ActivityTermIndexFactory.create(dropBoxViewRequest);

        //查询数据
        Result<List<String>> channelOutCodeListResult = activityTermIndexEntity.queryChannelIds();

        if (CollectionUtils.isEmpty(channelOutCodeListResult.getResult())) {
            return new CommonDropBox();
        }
        List<String> outCodeList = channelOutCodeListResult.getResult();

        return obtainCommonDropBox(outCodeList, channelOutCodeListResult.getTotal(),
                propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.
                        CHANNEL_CODE.getKey()).obtainCodeAndDescMap(outCodeList, false));
    }


    @Override
    public ActivityDropBoxViewResponse queryActivityIdAndTermId() {
        return ActivityQueryService.super.queryActivityIdAndTermId();
    }

    @Override
    @FacadeInvoker(value = "查询销售组织", errorCode = "OTS-08-001-01-16-026")
    public CommonDropBox queryOrganizationForDropBox(DropBoxViewRequest dropBoxViewRequest) {
        QueryPromotionPageListRequest request = new QueryPromotionPageListRequest();
        authorityDetail(request);
        List salesOrganizationId = request.getSalesOrganizationId();
        dropBoxViewRequest.setCodeList(salesOrganizationId);
        //查询销售组织外部编码
        ActivityTermIndexEntity activityTermIndexEntity = ActivityTermIndexFactory.create(dropBoxViewRequest);
        Result<List<String>> salesOrganizationOutCodeListResult = activityTermIndexEntity.querySaleOrganizationIds();
        if (CollectionUtils.isEmpty(salesOrganizationOutCodeListResult.getResult())) {
            return new CommonDropBox();
        }
        List<String> outCodeList = salesOrganizationOutCodeListResult.getResult();
        return obtainCommonDropBox(outCodeList, salesOrganizationOutCodeListResult.getTotal(),
                propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.
                        ORG_SALES_ORGANIZATION_CODE.getKey()).obtainCodeAndDescMap(outCodeList, false));
    }

    @Override
    @FacadeInvoker(value = "查询客户", errorCode = "OTS-08-001-01-16-027")
    public CommonDropBox queryCustomerForDropBox(DropBoxViewRequest dropBoxViewRequest) {
        ActivityTermIndexEntity activityTermIndexEntity = ActivityTermIndexFactory.create(dropBoxViewRequest);

        //查询客户外部编码list
        Result<List<String>> clientOutCodeListResult = activityTermIndexEntity.queryCustomerIds();

        if (CollectionUtils.isEmpty(clientOutCodeListResult.getResult())) {
            return new CommonDropBox();
        }
        List<String> outCodeList = clientOutCodeListResult.getResult();
        return obtainCommonDropBox(outCodeList, clientOutCodeListResult.getTotal(),
                propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.
                        CUSTOM_CODE.getKey()).obtainCodeAndDescMap(outCodeList, false));
    }


    @Override
    @FacadeInvoker(value = "查询货品", errorCode = "OTS-08-001-01-16-028")
    public CommonDropBox queryItemForDropBox(DropBoxViewRequest dropBoxViewRequest) {
        ActivityTermIndexEntity activityTermIndexEntity = ActivityTermIndexFactory.create(dropBoxViewRequest);

        //查询货品外部编码list
        Result<List<String>> itemOutCodeListResult = activityTermIndexEntity.queryItemIds();
        List<String> outCodeList = itemOutCodeListResult.getResult();
        return obtainCommonDropBox(outCodeList, itemOutCodeListResult.getTotal(),
                propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.
                        MATERIAL_CODE.getKey()).obtainCodeAndDescMap(outCodeList, false));
    }

    //下拉框数据通用组装方法
    public CommonDropBox obtainCommonDropBox(List<String> outCodeList, Integer total, Map<String, String> codeAndDescMap) {
        CommonDropBox commonDropBox = new CommonDropBox();
        commonDropBox.setResult(null);
        commonDropBox.setTotal(0L);
        if (CollectionUtils.isEmpty(outCodeList)) {
            return commonDropBox;
        }
        commonDropBox.setTotal(0L);

        //没有在主数据查到对应关系时，outCode即为desc
        if (MapUtils.isEmpty(codeAndDescMap)) {
            return obtainLabelNameAndCodeList(commonDropBox, outCodeList, null, false);
        }

        return obtainLabelNameAndCodeList(commonDropBox, outCodeList, codeAndDescMap, true);
    }

    //用于获取编码和描述信息的对应关系,isExistData表示调用基线接口后是否有查询到数据
    private CommonDropBox obtainLabelNameAndCodeList(CommonDropBox commonDropBox, List<String> outCodeList,
                                                     Map<String, String> outCodeAndNameMap, Boolean isExistData) {

        List<DropBoxCommon> dropBoxCommonList = Lists.newArrayList();

        if (isExistData) {
           outCodeList.stream().forEach(e -> {

                String name = outCodeAndNameMap.get(e);
                //主数据有对应关系时
                if (StringUtils.isNotBlank(name)) {
                    DropBoxCommon dropBoxCommon = new DropBoxCommon();
                    dropBoxCommon.setLabel(outCodeAndNameMap.get(e) + "(" + e + ")");
                    dropBoxCommon.setValue(e);
                    dropBoxCommonList.add(dropBoxCommon);
                }
//                else {
//                    dropBoxCommon.setLabel(item + "(" + item + ")");
//                    dropBoxCommon.setValue(item);
//                }
            });
        }
//        else {
//            dropBoxCommonList = outCodeList.stream().map(item -> {
//                DropBoxCommon dropBoxCommon = new DropBoxCommon();
//                dropBoxCommon.setLabel(item + "(" + item + ")");
//                dropBoxCommon.setValue(item);
//                return dropBoxCommon;
//            }).collect(Collectors.toList());
//        }

        commonDropBox.setResult(dropBoxCommonList);
        commonDropBox.setTotal(dropBoxCommonList.size()+0L);
        return commonDropBox;
    }


    @Override
    public Result<List<ActivityTermViewResponse>> queryPromotionDetailPageList(ActivityDetailQueryViewRequest request) {
        //工厂方式获取entity
        ActivityTermEntity activityTermEntity = ActivityTermFactory.create(request);
        //查询数据
        return activityTermEntity.loadPromotionDetailPageList();
    }

    @Override
    @FacadeInvoker(value = "查询坎级详情", errorCode = "OTS-08-001-01-16-029")
    public Result<List<SegmentedDetailViewResponse>> querySegmentDetailPageList(SegmentedDetailQueryViewRequest request) {
        //工厂方式获取entity
        SegmentedActivityTermEntity segmentedActivityTermEntity = SegmentedActivityTermFactory.create(request);
        //查询数据
        return segmentedActivityTermEntity.loadSegmentDetailPageList();
    }

    @Override
    @FacadeInvoker(value = "查询活动使用详情", errorCode = "OTS-08-001-01-16-030")
    public Result<List<ActivityUseDetailViewResponse>> queryPromotionUsedDetailPageList(ActivityUseDetailQueryViewRequest request) {
        //工厂方式获取entity
        ActivityUseRecordRelationEntity activityUseRecordRelationEntity = ActivityUseRecordRelationFactory.create(request);
        //查询数据
        return activityUseRecordRelationEntity.loadPromotionUsedDetailPageList();
    }

    @Override
    public Result<List<ClientResponse>> queryClientList(ActivityQueryViewRequest activityQueryViewRequest) {
        //获取客户编码
        ActivityTitleEntity activityTitleEntity = ActivityTitleFactory.create(activityQueryViewRequest);
        Result<List<String>> customerIds = activityTitleEntity.queryCustomerCodes();

        if (CollectionUtils.isEmpty(customerIds.getResult())) {
            return Result.success(new ArrayList<>());
        }

        //获取客户信息
        Map<String, String> customerCodeAndDescMap = propertyProcessManager.getPropertyProcess(
                DimensionPropertyEnum.CUSTOM_CODE.getKey()).obtainCodeAndDescMap(customerIds.getResult(), false);
        //获取客户地址信息（送达方）
        Map<String, String> customerAddressCodeAndDescMap = propertyProcessManager.getPropertyProcess(
                DimensionPropertyEnum.CUSTOMER_SEND_ADDRESS_CODE.getKey()).obtainCodeAndDescMap(customerIds.getResult(), false);

        Map<String, String> map = Maps.newHashMap();
        map.putAll(customerAddressCodeAndDescMap);
        map.putAll(customerCodeAndDescMap);

        if (MapUtils.isEmpty(map)) {
            return Result.success(new ArrayList<>());
        }

        List<ClientResponse> clientResponses = map.keySet().stream().map(item ->
                {
                    ClientResponse clientResponse = new ClientResponse();
                    clientResponse.setClientId(item);
                    clientResponse.setClientName(map.get(item));
                    return clientResponse;
                }
        ).collect(Collectors.toList());

        Result<List<ClientResponse>> result = Result.success(clientResponses);
        result.setTotal(customerIds.getTotal());
        return result;
    }

    @Override
    public Result<List<ItemResponse>> queryItemList(ActivityQueryViewRequest activityQueryViewRequest) {
        //获取原品编码
        ActivityTermEntity activityTermEntity = ActivityTermFactory.create(activityQueryViewRequest);
        Result<List<String>> itemCodes = activityTermEntity.queryItemCodes();
        if (CollectionUtils.isEmpty(itemCodes.getResult())) {
            return Result.success(new ArrayList<>());
        }

        Map<String, String> map = propertyProcessManager.getPropertyProcess(
                DimensionPropertyEnum.MATERIAL_CODE.getKey()).obtainCodeAndDescMap(itemCodes.getResult(), false);

        if (MapUtils.isEmpty(map)) {
            return Result.success(new ArrayList<>());
        }
        List<ItemResponse> itemResponses = map.keySet().stream().map(item ->
                {
                    ItemResponse itemResponse = new ItemResponse();
                    itemResponse.setItemId(item);
                    itemResponse.setItemName(map.get(item));
                    return itemResponse;
                }
        ).collect(Collectors.toList());

        Result<List<ItemResponse>> result = Result.success(itemResponses);
        result.setTotal(itemCodes.getTotal());
        return result;
    }


    @Override
    public Result<List<GiftResponse>> queryGiftList(ActivityQueryViewRequest activityQueryViewRequest) {
        //获取赠品编码
        ActivityTermEntity activityTermEntity = ActivityTermFactory.create(activityQueryViewRequest);
        Result<List<String>> giftCodes = activityTermEntity.queryGiftCodes();
        if (CollectionUtils.isEmpty(giftCodes.getResult())) {
            return Result.success(new ArrayList<>());
        }

        Map<String, String> map = propertyProcessManager.getPropertyProcess(
                DimensionPropertyEnum.MATERIAL_CODE.getKey()).obtainCodeAndDescMap(giftCodes.getResult(), false);

        if (MapUtils.isEmpty(map)) {
            return Result.success(new ArrayList<>());
        }
        List<GiftResponse> giftResponses = map.keySet().stream().map(item ->
                {
                    GiftResponse giftResponse = new GiftResponse();
                    giftResponse.setGiftId(item);
                    giftResponse.setGiftName(map.get(item));
                    return giftResponse;
                }
        ).collect(Collectors.toList());

        Result<List<GiftResponse>> result = Result.success(giftResponses);
        result.setTotal(giftCodes.getTotal());
        return result;
    }


    /**
     * 批量查询可参加的活动列表_有转码功能的接口 内部->外部
     *
     * @param queryActivityRequest 查询活动请求
     * @return 活动结果
     */
    @Override
    @FacadeInvoker(value = "批量查询活动", errorCode = "OTS-08-001-01-16-031")
    public Result<ActivityResponse> batchQueryCanUsingActivityExpand(QueryActivityRequest queryActivityRequest) {
        //校验批次查询可用的活动
        QueryActivityRequest newRequest = new QueryActivityRequest();

        copyValue(queryActivityRequest, newRequest);
        checkBatchQueryCanUsingActivityParam(newRequest);

        //获取所有的销售组织编码
        List<String> originSalesOrganizationList = newRequest.getActivityInfoRequestList().stream().
                map(item -> item.getSalesOrganization()).collect(Collectors.toList());
        //获取所有的业务渠道编码
        List<String> originBusinessChannelList = newRequest.getActivityInfoRequestList().stream().
                filter(item -> StringUtils.isNotBlank(item.getBusinessChannel())).
                map(s -> s.getBusinessChannel()).collect(Collectors.toList());
        //获取所有的货品编码
        List<String> originItemList = new ArrayList<>();
        newRequest.getActivityInfoRequestList().stream().forEach(activityInfoRequest -> {
            List<String> itemIds = activityInfoRequest.getItemList().stream().
                    map(item -> item.getItemId()).collect(Collectors.toList());
            originItemList.addAll(itemIds);
        });


        if (Objects.isNull(newRequest.getFeatures()) || StringUtils.isBlank(newRequest.getFeatures().get("codeFlag"))) {
            log.error("请传编码转换标识，内部转外部:inner_code_to_out_code,外部转内部:out_code_to_inner_code" +
                    "participateActivityRequest = {}", JSONObject.toJSONString(newRequest));
            log.error("ActivityQueryServiceImpl#batchQueryCanUsingActivityExpand_fail");
            throw new FacadeException("OTS-08-001-01-16-018");
        }

        if (newRequest.getFeatures().get("codeFlag").equals(PlatformCodeFlagEnum.OUT_CODE_TO_INNER_CODE.getCode())) {
            return batchQueryCanUsingActivity(newRequest);
        }

        if (!newRequest.getFeatures().get("codeFlag").equals(PlatformCodeFlagEnum.INNER_CODE_TO_OUT_CODE.getCode())) {
            log.error("请传正确的编码转换标识，内部转外部:inner_code_to_out_code,外部转内部:out_code_to_inner_code"
                    + "participateActivityRequest = {}", JSONObject.toJSONString(newRequest));
            log.error("ActivityQueryServiceImpl#batchQueryCanUsingActivityExpand_fail");
            throw new FacadeException("OTS-08-001-01-16-019");
        }

        //获取销售组织内外部编码映射关系
        Map<String, String> salesOrganizationMap = propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.ORG_SALES_ORGANIZATION_CODE.getKey()).
                obtainInnerCodeAndOuterCodeMap(originSalesOrganizationList, true);
        //Map<String, OrganizationSDO> salesOrganizationMap = obtainSalesOrganizationMap(originSalesOrganizationList, true);
        if (MapUtils.isEmpty(salesOrganizationMap)) {
            log.error("未查询到销售组织外部编码，请排查是否存在映射关系 = {}", originSalesOrganizationList);
            log.error("ActivityQueryServiceImpl#batchQueryCanUsingActivityExpand_fail");
            throw new FacadeException("OTS-08-001-01-16-022");
        }
        //获取业务渠道内外部编码映射关系
        Map<String, String> channelMap = propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.CHANNEL_CODE.getKey())
                .obtainInnerCodeAndOuterCodeMap(originBusinessChannelList,true);
//        Map<String, Map<String, String>> channelMap = obtainChannelMap(originBusinessChannelList, true);
        if (MapUtils.isEmpty(channelMap)) {
            log.error("未查询到业务渠道外部编码，请排查是否存在映射关系 = {}", originBusinessChannelList);
            log.error("ActivityQueryServiceImpl#batchQueryCanUsingActivityExpand_fail");
            throw new FacadeException("OTS-08-001-01-16-023");
        }
        //获取货品编码的对应关系（内部编码:外部编码）
        Map<String, String> itemMap = propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.MATERIAL_CODE.getKey())
                .obtainInnerCodeAndOuterCodeMap(originItemList, true);
//        Map<String, ScItemSDO> itemMap = obtainItemMap(originItemList, true);
        if (MapUtils.isEmpty(itemMap)) {
            log.error("未查询到货品外部编码，请查询主数据该货品是否可用 = {}", originItemList);
            log.error("ActivityQueryServiceImpl#batchQueryCanUsingActivityExpand_fail");
            throw new FacadeException("OTS-08-001-01-16-021");
        }

        //外部编码入参实体
        List<ActivityInfoRequest> activityInfoRequestConversionList = new ArrayList<>();
        List<ActivityInfoRequest> activityInfoRequestOriginList = newRequest.getActivityInfoRequestList();
        activityInfoRequestOriginList.forEach(item -> {
            ActivityInfoRequest activityInfoRequest = new ActivityInfoRequest();
            BeanUtils.copyProperties(item, activityInfoRequest);
            //销售组织转码
            String innerSalesOrganizationCode = item.getSalesOrganization();
            String organizationCode = salesOrganizationMap.get(innerSalesOrganizationCode);
//            OrganizationSDO organizationSDO = salesOrganizationMap.get(innerSalesOrganizationCode);
            if (StringUtils.isBlank(organizationCode)) {
                log.error("ActivityQueryServiceImpl#batchQueryCanUsingActivityExpand_fail");
                log.error("未查询到该销售组织外部编码，请排查是否存在映射关系 = {}", item);
                throw new FacadeException("OTS-08-001-01-16-022");
            }
            activityInfoRequest.setSalesOrganization(organizationCode);
//            activityInfoRequest.setSalesOrganization(organizationSDO.getOutCode());

            //业务渠道转码
            String innerBusinessChannelCode = item.getBusinessChannel();
           String channelOutCode = channelMap.get(innerBusinessChannelCode);
//            Map<String, String> outerBusinessChannelCodeMap = channelMap.get(innerBusinessChannelCode);
            if (StringUtils.isBlank(channelOutCode)) {
                log.error("ActivityQueryServiceImpl#batchQueryCanUsingActivityExpand_fail");
                log.error("未查询到业务渠道外部编码，请排查是否存在映射关系 = {}", item);
                throw new FacadeException("OTS-08-001-01-16-023");
            }
            activityInfoRequest.setBusinessChannel(channelOutCode);

            //货品id转码
            List<ActivityItemInfoRequest> outerActivityItemInfoRequestList = item.getItemList().stream().map(activityItemInfoRequest -> {
                ActivityItemInfoRequest request = new ActivityItemInfoRequest();
                BeanUtils.copyProperties(activityItemInfoRequest, request);

                String itemOutCode = itemMap.get(activityItemInfoRequest.getItemId());
//                ScItemSDO scItemSDO = itemMap.get(activityItemInfoRequest.getItemId());
                //转码
                if (StringUtils.isBlank(itemOutCode)) {
                    log.error("ActivityQueryServiceImpl#batchQueryCanUsingActivityExpand_fail");
                    log.error("未查询到该货品外部编码，请查询主数据该货品是否可用 = {}", activityItemInfoRequest);
                    throw new FacadeException("OTS-08-001-01-16-021");
                }
                request.setItemId(itemOutCode);
                return request;
            }).collect(Collectors.toList());
            activityInfoRequest.setItemList(outerActivityItemInfoRequestList);
            activityInfoRequestConversionList.add(activityInfoRequest);

        });

        //调用活动查询---start
        newRequest.setActivityInfoRequestList(activityInfoRequestConversionList);
        Result<ActivityResponse> activityResponseResult =
                applicationContext.getBean(ActivityQueryServiceImpl.class).batchQueryCanUsingActivity(newRequest);

        if (CollectionUtils.isEmpty(activityResponseResult.getResult().getActivityInfoResponseList())) {
            log.info("未查询到可用活动 = {}", JSONObject.toJSONString(activityResponseResult));
            return Result.success(new ActivityResponse());
        }
        //调用活动查询---end

        List<ActivityInfoResponse> activityInfoResponseList = activityResponseResult.getResult().getActivityInfoResponseList();

        //获取所有的货品外部编码
        Set<String> outItemList = Sets.newHashSet();
        activityInfoResponseList.forEach(item -> {
            List<ActivityTermResponse> activityTermList = item.getActivityTermList();
            activityTermList.forEach(subItem -> {
                if (Objects.nonNull(subItem) && StringUtils.isNotBlank(subItem.getItemId())) {
                    outItemList.add(subItem.getItemId());
                }
                if (CollectionUtils.isNotEmpty(subItem.getGiftList())) {
                    subItem.getGiftList().stream().filter(gift -> StringUtils.isNotBlank(gift.getItemId()))
                            .forEach(gift -> outItemList.add(gift.getItemId()));
                }
            });
        });

        //获取货品外部：内部编码映射关系
        Map<String, String> itemOuterMap = propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.MATERIAL_CODE.getKey())
                .obtainInnerCodeAndOuterCodeMap(outItemList.stream().collect(Collectors.toList()), false);

        //获取所有的活动类型
        List<String> activityTypes = activityResponseResult.getResult().getActivityInfoResponseList().stream().
                map(e -> e.getActivityFacadeCode()).distinct().collect(Collectors.toList());

        //校验货品
//        if (MapUtils.isEmpty(itemOuterMap) && !activityTypes.contains(ActivityTypeEnum.REPLENISHMENT.getValue())) {
//            log.error("未查询到该货品内部编码，请查询主数据该货品是否可用 = {}", outItemList);
//            throw new FacadeException("OTS-08-001-01-16-021");
//        }

        convertBatchQueryActivityResult(activityResponseResult, itemOuterMap);

        return activityResponseResult;

    }

    private void convertBatchQueryActivityResult(Result<ActivityResponse> activityResponseResult, Map<String, String> itemOuterMap) {
        activityResponseResult.getResult().getActivityInfoResponseList().forEach(e -> {
            e.getActivityTermList().forEach(term -> {
                String itemId = term.getItemId();
                if (StringUtils.isNotBlank(itemId)) {
                    String itemInnerCode = itemOuterMap.get(itemId);
                    if (StringUtils.isNotBlank(itemInnerCode)) {
                        term.setItemId(itemInnerCode);
                    }
                }
                if(CollectionUtils.isNotEmpty(term.getGiftList())){
                    term.getGiftList().forEach(gift -> {
                        String giftId = gift.getItemId();
                        if (StringUtils.isNotBlank(giftId)) {
                            String giftInnerCode = itemOuterMap.get(giftId);
                            if (StringUtils.isBlank(giftInnerCode)) {
                                log.error("ActivityQueryServiceImpl#batchQueryCanUsingActivityExpand_fail");
                                log.error("未查询到该赠品内部编码，请查询主数据该货品是否可用 = {}", giftId);
                                throw new FacadeException("OTS-08-001-01-16-021");
                            }
                            gift.setItemId(giftInnerCode);
                        }
                    });

                    //平摊逻辑不在这做处理
//                    String giftActivityType = term.getGiftActivityType();
//                    //对普通多赠品活动的赠品数量平摊
//                    if (GiftTypeEnum.MULTIPLY_GIFT.getCode().equals(giftActivityType)) {
//                        Integer giftCount = term.getGiftList().get(0).getItemQuantity();
//
//                        if (Objects.nonNull(giftCount) && giftCount > 0) {
//                            List<ActivityItemInfo> distribute = term.getGiftList();
//                            int avg = giftCount / term.getGiftList().size();
//
//                            int distributed = 0;
//                            for (int i = 0; i < distribute.size() - 1; i++) {
//                                distribute.get(i).setItemQuantity(avg);
//                                distributed += avg;
//                            }
//                            //将剩余的分配给最后一个
//                            int remainingUnDistribute = giftCount - distributed;
//                            distribute.get(distribute.size() - 1).setItemQuantity(remainingUnDistribute);
//                        }
//
//                    }
                }
            });
        });
    }

    private void copyValue(QueryActivityRequest queryActivityRequest, QueryActivityRequest newRequest) {
        newRequest.setFeatures(queryActivityRequest.getFeatures());
        List<ActivityInfoRequest> newActivityInfoRequestList = queryActivityRequest.getActivityInfoRequestList().stream().map(request -> {
            ActivityInfoRequest newActivityInfoRequest = new ActivityInfoRequest();
            //更换成自己的当前时间，使用的该方法的时候要注意
            newActivityInfoRequest.setActivityUseTime(request.getActivityUseTime());
            newActivityInfoRequest.setBusinessChannel(request.getBusinessChannel());
            newActivityInfoRequest.setSalesOrganization(request.getSalesOrganization());
            newActivityInfoRequest.setClientId(request.getClientId());
            newActivityInfoRequest.setMainOrderId(request.getMainOrderId());
            newActivityInfoRequest.setSubOrderId(request.getSubOrderId());
            newActivityInfoRequest.setDeliveryDate(request.getDeliveryDate());
            newActivityInfoRequest.setOrderType(request.getOrderType());
            newActivityInfoRequest.setShipAddressId(request.getShipAddressId());
            List<ActivityItemInfoRequest> oldItemList = request.getItemList();
            if (CollectionUtils.isNotEmpty(oldItemList)) {
                List<ActivityItemInfoRequest> newItemInfo = oldItemList.stream().map(item -> {
                    ActivityItemInfoRequest newItem = new ActivityItemInfoRequest();
                    newItem.setItemId(item.getItemId());
                    newItem.setItemQuantity(item.getItemQuantity());
                    newItem.setSalesUnit(item.getSalesUnit());
                    return newItem;
                }).collect(Collectors.toList());
                newActivityInfoRequest.setItemList(newItemInfo);
            }
            return newActivityInfoRequest;
        }).collect(Collectors.toList());

        newRequest.setActivityInfoRequestList(newActivityInfoRequestList);
    }

    //获取货品编码的对应关系
    public Map<String, ScItemSDO> obtainItemMap(List<String> itemList, boolean innerCode) {
        SearchScItemByDBWhenDegradedRequest searchScItemRequest = new SearchScItemByDBWhenDegradedRequest();
        Map<String, Object> searchReqDTO = new HashMap<>();

        //有null元素时查不到结果,需要排除
        itemList.remove(null);
        if (innerCode) {
            searchReqDTO.put("scItemIds", itemList);
        } else {
            searchReqDTO.put("outerIdList", itemList);
        }
        searchScItemRequest.setSearchReqDTO(searchReqDTO);
        searchScItemRequest.setPageSize(2000);
        Map<String, ScItemSDO> itemInnerAndOutMap = Maps.newHashMap();
        Result<List<ScItemSDO>> scItemListResult = baseDataService.searchScItemByDBWhenDegraded(searchScItemRequest);
        if (Objects.isNull(scItemListResult)) {
            log.error("接口调用异常，请排查 com.epoch.app.bcorder.service.BaseDataService.searchScItemByDBWhenDegraded() = {}",
                    JSONObject.toJSONString(searchScItemRequest));
            throw new FacadeException("OTS-08-003-01-16-001");
        }

        if (org.apache.commons.collections.CollectionUtils.isEmpty(scItemListResult.getResult())) {
            return itemInnerAndOutMap;
        }
        List<ScItemSDO> result = scItemListResult.getResult();
        if (innerCode) {
            //内部编码
            return result.stream().collect(Collectors.toMap(ScItemSDO::getScItemId, Function.identity()));
        } else {
            //外部编码
            return result.stream().collect(Collectors.toMap(ScItemSDO::getOuterId, Function.identity()));
        }
    }


    //获取销售组织编码的对应关系
    public Map<String, OrganizationSDO> obtainSalesOrganizationMap(List<String> originSalesOrganizationList, boolean innerCode) {
        Map<String, OrganizationSDO> orgSalesOrganizationCodeMap = Maps.newHashMap();

        Map<String, Object> orgSalesOrganizationCodeResult = Maps.newHashMap();
        if (innerCode) {
            //根据内部编码查询
            BaselineGetOrganizationByIdsRequest baselineGetOrganizationByIdsRequest = new BaselineGetOrganizationByIdsRequest();
            baselineGetOrganizationByIdsRequest.setIds(originSalesOrganizationList);
            baselineGetOrganizationByIdsRequest.setStatus(1);
            orgSalesOrganizationCodeResult = (Map<String, Object>) baseDataService.baselineGetOrganizationByIds(baselineGetOrganizationByIdsRequest);
        } else {
            BaselineGetOrganizationByOutCodesRequest baselineGetOrganizationByOutCodesRequest = new BaselineGetOrganizationByOutCodesRequest();
            baselineGetOrganizationByOutCodesRequest.setOutCodes(originSalesOrganizationList);
            baselineGetOrganizationByOutCodesRequest.setStatus(1);
            //根据外部编码查询
            orgSalesOrganizationCodeResult = (Map<String, Object>) baseDataService.baselineGetOrganizationByOutCodes(baselineGetOrganizationByOutCodesRequest);
        }


        if (Objects.isNull(orgSalesOrganizationCodeResult)) {
            log.error("接口调用异常，请排查 com.epoch.app.bcorder.service.BaseDataService.baselineGetOrganizationByIds() = {}",
                    JSONObject.toJSONString(originSalesOrganizationList));
            throw new FacadeException("OTS-08-003-01-16-001");
        }
        List<Map<String, Object>> orgSalesOrganizationCodeResultList = (List<Map<String, Object>>) orgSalesOrganizationCodeResult.get("result");
        if (org.apache.commons.collections.CollectionUtils.isEmpty(orgSalesOrganizationCodeResultList)) {
            return new HashMap<>();
        }
        List<OrganizationSDO> organizationSDOList = orgSalesOrganizationCodeResultList.stream().
                map(item -> JSONObject.parseObject(JSONObject.toJSONString(item.get("organizationSDO")), OrganizationSDO.class)).
                collect(Collectors.toList());
        organizationSDOList.forEach(item -> {
            if (innerCode) {
                orgSalesOrganizationCodeMap.put(item.getId(), item);
            } else {
                orgSalesOrganizationCodeMap.put(item.getOutCode(), item);
            }
        });

        return orgSalesOrganizationCodeMap;
    }

    //获取业务渠道编码对应关系
    public Map<String, Map<String, String>> obtainChannelMap(List<String> businessChannelList, boolean innerCode) {
        BaselineBatchQueryChannelsRequest baselineBatchQueryChannelsRequest = new BaselineBatchQueryChannelsRequest();
        //内部编码标识
        businessChannelList.remove(null);
        if (innerCode) {
            baselineBatchQueryChannelsRequest.setChannelCodes(businessChannelList);
        } else {
            baselineBatchQueryChannelsRequest.setOutCodes(businessChannelList);
        }

        Map<String, Map<String, String>> channelCodeMap = Maps.newHashMap();

        Object channelResult = baseDataService.baselineBatchQueryChannels(baselineBatchQueryChannelsRequest);
        if (Objects.isNull(channelResult)) {
            log.error("接口调用异常，请排查 com.epoch.app.bcorder.service.BaseDataService.baselineBatchQueryChannels() = {}",
                    JSONObject.toJSONString(baselineBatchQueryChannelsRequest));
            throw new FacadeException("OTS-08-003-01-16-001");
        }
        Map<String, Object> channelResultMap = (Map<String, Object>) channelResult;

        Map<String, Object> channelMap = (Map<String, Object>) channelResultMap.get("result");

        List<Map<String, Object>> channelList = (List<Map<String, Object>>) channelMap.get("result");
        if (CollectionUtils.isNotEmpty(channelList)) {
            channelList.stream().filter(item -> Objects.nonNull(item) && StringUtils.isNotBlank((String) item.
                    get("channelCode")) && StringUtils.isNotBlank((String) item.get("outCode"))).forEach(item -> {
                Map<String, String> map = Maps.newHashMap();
                map.put("outCode", (String) item.get("outCode"));
                map.put("channelName", (String) item.get("channelName"));
                map.put("channelId", (String) item.get("channelId"));
                map.put("channelCode", (String) item.get("channelCode"));
                if (innerCode) {
                    channelCodeMap.put((String) item.get("channelCode"), map);
                } else {
                    channelCodeMap.put((String) item.get("outCode"), map);
                }
            });
        }
        return channelCodeMap;
    }


    @Override
    @FacadeInvoker(value = "批量查询活动", errorCode = "OTS-08-001-01-16-031")
    public Result<ActivityResponse> batchQueryCanUsingActivity(QueryActivityRequest request) {

//        1、校验批次查询可用的活动
        checkBatchQueryCanUsingActivityParam(request);

        ActivityResponse activityResponse = new ActivityResponse();

        try {
            //2. 缓存到线程上下文中，在计算组合促销的时候使用，记录参加分析的主子单关联信息
            CombinationItemStore store = CombinationItemStore.of(request);
            CustumerCombinationItemThreadLocal.set(store);

            //3. 缓存到线程上下文中，在计算坎级搭赠的时候使用，同一个主单下，
            // 只有第一个子单可以编辑坎级搭赠，其余子单不能编辑同时命中的坎级搭赠
            Map<String, Map<String,Map<String,Boolean>>> activityMainLineChooseMap=new HashMap<>();
            for (ActivityInfoRequest activityInfoRequest : request.getActivityInfoRequestList()) {
                Map<String, Map<String,Boolean>> orDefault = activityMainLineChooseMap.getOrDefault(activityInfoRequest.getMainOrderId(), new HashMap<>());
                orDefault.put(activityInfoRequest.getSubOrderId(),new HashMap<>());
                activityMainLineChooseMap.put(activityInfoRequest.getMainOrderId(),orDefault);
            }
            ActivityMainLineChooseThreadLocal.set(activityMainLineChooseMap);

            //搭赠活动是否有禁止选择赠品的行为（组合满量搭赠有）
            Map<String,Boolean> lineActivityChooseMap=new HashMap<>();
            ActivityLineNeedChooseThreadLocal.set(lineActivityChooseMap);

            List<ActivityInfoResponse> activityInfoResponseList = new ArrayList<>();
            for (ActivityInfoRequest activityInfoRequest : request.getActivityInfoRequestList()) {

                List<ActivityEntity> activityEntityList = ActivityFactory.create(activityInfoRequest);
                if (CollectionUtils.isEmpty(activityEntityList)) {
                    log.info("未查询到可参与的活动");
                    continue;
                }
                activityEntityList.forEach(activity -> {

                    ActivityInfoResponse infoResponse = activity.queryCanUsingActivityTerm(activityInfoRequest);

//                  1. 补货订单类型，补货活动添加
                    if (ActivityOrderTagEnum.REPLENISH_ORDER.getCode().equals(activityInfoRequest.getOrderType())
                            && replenishList.contains(infoResponse.getActivityFacadeCode())) {
                        activityInfoResponseList.add(infoResponse);
                    }

//                  2.非补货类型订单，需要判断活动项目列表是否为空，不为空，可以返回
                    if (!ActivityOrderTagEnum.REPLENISH_ORDER.getCode().equals(activityInfoRequest.getOrderType())
                            && CollectionUtils.isNotEmpty(infoResponse.getActivityTermList())) {
                        String activityId = infoResponse.getActivityId();
                        String mainOrderId = infoResponse.getMainOrderId();
                        Boolean needWriteFilterFlag = ActivityLineNeedChooseThreadLocal.get().getOrDefault((mainOrderId + "-" + activityId), false);

                        Map<String, Map<String, Map<String,Boolean>>> mainLineChoose = ActivityMainLineChooseThreadLocal.get();
                        Map<String, Boolean> chooseFlagMap = mainLineChoose.get(infoResponse.getMainOrderId()).get(infoResponse.getSubOrderId());

                        if (needWriteFilterFlag){
                            infoResponse.setDisableChooseFlag(chooseFlagMap.getOrDefault(activityId,true));
                        }
                        activityInfoResponseList.add(infoResponse);
                    }
                });
            }

            //循环判断同主单同同组合搭赠活动是否倍率一致

            activityResponse.setActivityInfoResponseList(obtainItemName(activityInfoResponseList));
        } catch (Exception e) {
            //这里主要是用 finally ，不是为了用 try-catch
            log.error("ActivityQueryServiceImpl#batchQueryCanUsingActivity" + "_fail");
            throw e;
        } finally {
            //清空缓存
            CustumerCombinationItemThreadLocal.clear();
            ActivityMainLineChooseThreadLocal.clear();
            ActivityLineNeedChooseThreadLocal.clear();
            return Result.success(activityResponse);
        }
    }

    /**
     * 移除重复的子单请求参数
     * @param activityInfoRequestList 查询活动信息请求列表
     * @return
     */
    private List<ActivityInfoRequest> removeRepeatActivityInfoRequest(List<ActivityInfoRequest> activityInfoRequestList) {
        List<ActivityInfoRequest> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(activityInfoRequestList)) {
            return result;
        }

        Map<String, ActivityInfoRequest> map = new HashMap<>();
        for (ActivityInfoRequest infoRequest : activityInfoRequestList) {
            String key = infoRequest.getMainOrderId() + "_" + infoRequest.getSubOrderId();
            map.putIfAbsent(key, infoRequest);
        }

        return new ArrayList<>(map.values());
    }

    /**
     * 获取赠品名称
     *
     * @param activityInfoResponseList
     * @return
     */
    public List<ActivityInfoResponse> obtainItemName(List<ActivityInfoResponse> activityInfoResponseList) {

        if (CollectionUtils.isEmpty(activityInfoResponseList)) {
            return new ArrayList<>();
        }
        Set<String> giftSets = Sets.newHashSet();
        //获取所有的赠品外部编码list
        activityInfoResponseList.forEach(item -> {
            //获取赠品列表
            List<ActivityTermResponse> activityTermList = item.getActivityTermList();
            if (CollectionUtils.isNotEmpty(activityTermList)) {
                activityTermList.forEach(activityTermResponse -> {
                    if (Objects.nonNull(activityTermResponse)) {
                        List<ActivityItemInfo> giftList = activityTermResponse.getGiftList();
                        if (CollectionUtils.isNotEmpty(giftList)) {
                            giftList.stream().filter(ActivityItemInfo -> StringUtils.
                                    isNotBlank(ActivityItemInfo.getItemId())).forEach(gift -> giftSets.add(gift.getItemId()));
                        }
                    }
                });
            }
        });

        //如果列表是空的，直接返回
        if (CollectionUtils.isEmpty(giftSets)) {
            return activityInfoResponseList;
        }


        List<String> giftLists = new ArrayList<>(giftSets);

        //获取所有的货品信息map
        final Map<String, String> itemMap = propertyProcessManager.getPropertyProcess(DimensionPropertyEnum.MATERIAL_CODE.getKey())
                        .obtainCodeAndDescMap(giftLists,false);

        activityInfoResponseList.forEach(e->{
            e.getActivityTermList().forEach(term->{
                List<ActivityItemInfo> giftList = term.getGiftList();
                if(CollectionUtils.isNotEmpty(giftList)){
                    giftList.forEach(gift->{
                        gift.setItemName(itemMap.get(gift.getItemId()));
                    });
                }
            });
        });

        return activityInfoResponseList;


//        return activityInfoResponseList.stream().map(item -> {
//            ActivityInfoResponse activityInfoResponse = new ActivityInfoResponse();
//            BeanUtils.copyProperties(item, activityInfoResponse);
//
//            List<ActivityTermResponse> ActivityTermInfoList = item.getActivityTermList().stream().map(activityTerm -> {
//                ActivityTermResponse activityTermResponse = new ActivityTermResponse();
//                BeanUtils.copyProperties(activityTerm, activityTermResponse);
//                List<ActivityItemInfo> giftList = activityTerm.getGiftList();
////                替换赠品名称
//                if (CollectionUtils.isNotEmpty(giftList)) {
//                    List<ActivityItemInfo> activityItemInfos = giftList.stream().map(activityGiftInfo -> {
//
//                        ActivityItemInfo activityItemInfo = new ActivityItemInfo();
//                        BeanUtils.copyProperties(activityGiftInfo, activityItemInfo);
//                        ScItemSDO scItemSDO = itemMap.get(activityGiftInfo.getItemId());
//                        activityItemInfo.setItemName("未查询到货品名称，请查询主数据该货品是否可用，外部编码：itemOutCode = {}" +
//                                activityGiftInfo.getItemId());
//                        if (Objects.nonNull(scItemSDO)) {
//                            activityItemInfo.setItemName(scItemSDO.getTitle());
//                        }
//                        return activityItemInfo;
//
//                    }).collect(Collectors.toList());
//                    activityTermResponse.setGiftList(activityItemInfos);
//
//                }
//
//                return activityTermResponse;
//            }).collect(Collectors.toList());
//
//            activityInfoResponse.setActivityTermList(ActivityTermInfoList);
//            return activityInfoResponse;
//        }).collect(Collectors.toList());

    }

    /**
     * mock 结果
     *
     * @param request 用户请求
     * @return
     */
    private Result<ActivityResponse> mockBatchQueryCanUsingActivity(QueryActivityRequest request) {
//        1. 先校验一把
        checkBatchQueryCanUsingActivityParam(request);

        ActivityResponse response = new ActivityResponse();
        List<ActivityInfoResponse> infoResponseList = new ArrayList<>();
        request.getActivityInfoRequestList().forEach(e -> {
            ActivityInfoResponse infoResponse = new ActivityInfoResponse();
            infoResponse.setMainOrderId(e.getMainOrderId());
            infoResponse.setActivityId("mockActivityId001");
            infoResponse.setSubOrderId(e.getSubOrderId());
            infoResponse.setCurrency("CNY");
            infoResponse.setActivityNoteId("mockActivityNoteId001");
            infoResponse.setActivityStatus("normal");
            infoResponse.setActivityNoteName("七月份买 A增 B 活动");

            LocalDateTime localDate = LocalDateTime.now();
            Date date = Date.from(localDate.atZone(ZoneId.systemDefault()).toInstant());
            infoResponse.setOrderStartDate(date);

            LocalDateTime nextMonth = localDate.plusDays(30);
            Date endDate = Date.from(nextMonth.atZone(ZoneId.systemDefault()).toInstant());
            infoResponse.setOrderEndDate(endDate);

            infoResponse.setActivityTermList(mockBuildTermResponseList());
            infoResponseList.add(infoResponse);
        });

        response.setActivityInfoResponseList(infoResponseList);
        return Result.success(response);
    }

    /**
     * mock 结果
     *
     * @return
     */
    private List<ActivityTermResponse> mockBuildTermResponseList() {
        List<ActivityTermResponse> termResponseList = new ArrayList<>();

        Random random = new Random();
        int randomValue = random.nextInt(2);
        if (randomValue == 1) {
            ActivityTermResponse termResponse = mockBuildGiftTermResponse();
            termResponseList.add(termResponse);
        } else {
            ActivityTermResponse termResponse = mockBuildSpecialTermResponse();
            termResponseList.add(termResponse);
        }

        return termResponseList;
    }

    /**
     * @return
     */
    private ActivityTermResponse mockBuildSpecialTermResponse() {
        ActivityTermResponse termResponse = new ActivityTermResponse();
        /**
         * 活动项目 id
         */
        termResponse.setActivityTermId("T-02177830CXCP0001");
        /**
         * 业态	，必填
         */
        termResponse.setBusinessFormat("1301");
        /**
         * 品牌	，必填
         */
        termResponse.setBrand("130005");

        /**
         * 品类	，必填
         */
        termResponse.setItemCategory("101");
        /**
         * 品项	，必填
         */
        termResponse.setItemSubject("138");
        /**
         * 特价	，必填
         */
        termResponse.setSpecialOfferPrice("8.88");

        /**
         * 形式描述	，必填
         */
        termResponse.setFacadeDescription("特价活动");
        /**
         * 申请费用	必填
         */
        termResponse.setApplyFee(29120L);
        /**
         * 申请原品数量	Y
         */
        termResponse.setApplyItemQuantity(56);

        /**
         * 活动力度说明
         */
        termResponse.setIntensityOfActivityDesc("8件赠1件，赠品随车出库");

        /**
         * 总部投入金额
         */
        termResponse.setHeadQuartersInvestMoney(0L);
        /**
         * 公司自投金额
         */
        termResponse.setCompanySelfInvestMoney(0L);
        /**
         * 等级数量
         */
        termResponse.setGradeQuantity(0);

        /**
         * 活动发生数量
         */
        termResponse.setActivityOccupyQuantity(56);

        /**
         * 活动发生费用
         */
        termResponse.setActivityOccupyFee(29120L);

        /**
         * 活动剩余数量
         */
        termResponse.setActivityRemainingQuantity(0);

        /**
         * 活动剩余费用
         */
        termResponse.setActivityRemainingFee(0L);

        /**
         * 销售单位
         */
        termResponse.setSalesUnit("包");

        /**
         * 更新版本号
         */
        termResponse.setVersion(1);

        /**
         * 原品编码
         */
//        private String itemId;
        termResponse.setItemId("130100000002");

        /**
         * 原品数量
         */
        termResponse.setItemQuantity(57L);
//        /**
//         * 赠品编码
//         */
////        termResponse.setGiftId("130100000002");
//
//        /**
//         * 赠品数量
//         */
//        termResponse.setGiftQuantity(1L);


//        /**
//         * 赠品列表	和上面赠品编码不是一回事，这里这样定义主要是为了和数据库保持一致，之后会做调整
//         */
//        termResponse.setGiftList(mockBuildItemInfo());

        /**
         * 扩展参数
         */
        termResponse.setFeatures("字段的取法，买 5A 赠 2B 活动，");
        return termResponse;
    }

    /**
     * 构造活动项目返回结果
     *
     * @return
     */
    private ActivityTermResponse mockBuildGiftTermResponse() {
        ActivityTermResponse termResponse = new ActivityTermResponse();
        /**
         * 活动项目 id
         */
        termResponse.setActivityTermId("T-02177830CXCP0001");
        /**
         * 业态	，必填
         */
        termResponse.setBusinessFormat("1301");
        /**
         * 品牌	，必填
         */
        termResponse.setBrand("130005");

        /**
         * 品类	，必填
         */
        termResponse.setItemCategory("101");
        /**
         * 品项	，必填
         */
        termResponse.setItemSubject("138");
        /**
         * 特价	，必填
         */
        termResponse.setSpecialOfferPrice("0.00");

        /**
         * 形式描述	，必填
         */
        termResponse.setFacadeDescription("单品活动，公司追加费用至8赠1");
        /**
         * 申请费用	必填
         */
        termResponse.setApplyFee(29120L);
        /**
         * 申请原品数量	Y
         */
        termResponse.setApplyItemQuantity(56);

        /**
         * 活动力度说明
         */
        termResponse.setIntensityOfActivityDesc("8件赠1件，赠品随车出库");

        /**
         * 总部投入金额
         */
        termResponse.setHeadQuartersInvestMoney(0L);
        /**
         * 公司自投金额
         */
        termResponse.setCompanySelfInvestMoney(0L);
        /**
         * 等级数量
         */
        termResponse.setGradeQuantity(0);

        /**
         * 活动发生数量
         */
        termResponse.setActivityOccupyQuantity(56);

        /**
         * 活动发生费用
         */
        termResponse.setActivityOccupyFee(29120L);

        /**
         * 活动剩余数量	Y
         */
        termResponse.setActivityRemainingQuantity(0);

        /**
         * 活动剩余费用	Y
         */
        termResponse.setActivityRemainingFee(0L);

        /**
         * 销售单位
         */
        termResponse.setSalesUnit("包");

        /**
         * 更新版本号
         */
        termResponse.setVersion(1);

        /**
         * 原品编码
         */
//        private String itemId;
        termResponse.setItemId("130100000002");
        /**
         * 原品数量
         */
        termResponse.setItemQuantity(57L);
        /**
         * 赠品编码
         */
//        termResponse.setGiftId("130100000002");

        /**
         * 赠品数量
         */
        termResponse.setGiftQuantity(1L);


        /**
         * 赠品列表	和上面赠品编码不是一回事，这里这样定义主要是为了和数据库保持一致，之后会做调整
         */
        termResponse.setGiftList(mockBuildItemInfo());

        /**
         * 扩展参数
         */
        termResponse.setFeatures("字段的取法，买 5A 赠 2B 活动，");
        return termResponse;
    }

    /**
     * 构造赠品信息列表 todo qjg 上线要删除
     *
     * @return
     */
    private List<ActivityItemInfo> mockBuildItemInfo() {
        List<ActivityItemInfo> itemInfoList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            ActivityItemInfo itemInfo = new ActivityItemInfo();
            /**
             * 货品id，必填
             */
            Long itemId = 130100000003L + i;
            itemInfo.setItemId(itemId.toString());
            /**
             * 参加活动的货品数量，必填
             * 该字段也会被校验的，所以必传，如果超出了剩余的活动数量，返回校验不过的错误信息
             */
            itemInfo.setItemQuantity(1);
            /**
             * 货品名称, 必填
             * 添加该字段主要为了排查问题方便
             */
            itemInfo.setItemName("赠品1");

            /**
             * 货品单价，必填
             */
            itemInfo.setItemPrice(1L);

            /**
             * 销售单位
             */
            itemInfo.setItemName("PC");
            /**
             * 库存单位
             */
            itemInfo.setStockUnit("ST");
            /**
             * 转换单位
             */
            itemInfo.setConversionUnit("ST->PC");
            itemInfoList.add(itemInfo);
        }
        return itemInfoList;

    }

    /**
     * 校验活动
     *
     * @param checkRequest
     * @return
     */
    @Override
    public Result<CheckActivityResponse> checkActivity(ParticipateActivityRequest checkRequest) {
        checkActivityParam(checkRequest);

        CheckActivityResponse response = new CheckActivityResponse();
        List<CheckActivityInfoResponse> checkActivityInfoList = new ArrayList<>();
        response.setCheckActivityResposeList(checkActivityInfoList);

        checkRequest.getParticipateActivityInfoList().forEach(activityInfo -> {
            CheckActivityInfoResponse infoResponse = checkActivityInfo(activityInfo);
            checkActivityInfoList.add(infoResponse);
        });

        return Result.success(response);
    }

    /**
     * 校验活动信息
     *
     * @param activityInfo
     * @return
     */
    private CheckActivityInfoResponse checkActivityInfo(ParticipateActivityInfoRequest activityInfo) {
        ActivityEntity activityEntity = ActivityFactory.create(activityInfo);
        //创建校验活动返回结果
        CheckActivityInfoResponse checkActivityInfoResponse = new CheckActivityInfoResponse();

        //校验活动
        activityEntity.checkActivity(activityInfo, checkActivityInfoResponse);
        return checkActivityInfoResponse;
    }

    /**
     * 校验活动参数
     *
     * @param checkRequest
     */
    private void checkActivityParam(ParticipateActivityRequest checkRequest) {
//        todo qjg 这个地方需要补充下
        if (Objects.isNull(checkRequest)) {
            throw new FacadeException("");
        }

        if (CollectionUtils.isEmpty(checkRequest.getParticipateActivityInfoList())) {
            throw new FacadeException("");
        }

        checkRequest.getParticipateActivityInfoList().forEach(activityInfo -> {
            checkActivityInfoParam(activityInfo);
        });

    }

    /**
     * 校验ActivityInfo 参数
     *
     * @param activityInfo
     */
    private void checkActivityInfoParam(ParticipateActivityInfoRequest activityInfo) {
        /**
         * 客户 id
         */
        if (StringUtils.isBlank(activityInfo.getClientId())) {
            throw new FacadeException("OTS-08-001-01-16-009");
        }
        /**
         * 订单 ID
         */
        if (StringUtils.isBlank(activityInfo.getMainOrderId())) {
            throw new FacadeException("OTS-08-001-01-16-010");
        }
        /**
         * 子单 ID
         */
        if (StringUtils.isBlank(activityInfo.getSubOrderId())) {
            throw new FacadeException("OTS-08-001-01-16-011");
        }
        /**
         * 活动 id
         */
        if (StringUtils.isBlank(activityInfo.getActivityId())) {
            throw new FacadeException("OTS-08-001-01-16-012");
        }
        /**
         * 校验活动列表,当前应该只有一个活动项目，正常这里只能存放一个
         */
        if (Objects.isNull(activityInfo.getParticipateActivityTermRequest())) {
            throw new FacadeException("OTS-08-001-01-16-013");
        }
        /**
         * 交货日期
         */
        if (Objects.isNull(activityInfo.getDeliveryDate())) {
            throw new FacadeException("OTS-08-001-01-16-014");
        }
        /**
         * 活动使用日期
         */
        if (Objects.isNull(activityInfo.getActivityUseTime())) {
            throw new FacadeException("OTS-08-001-01-16-015");
        }
    }

    /**
     * 校验批次查询可用的活动
     *
     * @param request 请求参数
     */
    private void checkBatchQueryCanUsingActivityParam(QueryActivityRequest request) {
        if (CollectionUtils.isEmpty(request.getActivityInfoRequestList())) {
            log.error("批量查询活动请求参数错误：{}", request);
            throw new FacadeException("OTS-08-001-01-16-002");
        }

        request.getActivityInfoRequestList().forEach(infoRequest -> {
            //客户 id
            if (StringUtils.isBlank(infoRequest.getClientId())) {
                log.error("批量查询活动客户id参数错误：{}", infoRequest);
                throw new FacadeException("OTS-08-001-01-16-003");
            }

            /**
             * 主订单id
             */
            if (StringUtils.isBlank(infoRequest.getMainOrderId())) {
                log.error("批量查询活动主单号参数错误：{}", infoRequest);
                throw new FacadeException("OTS-08-001-01-16-004");
            }

            /**
             * 货品信息列表
             */
            if (CollectionUtils.isEmpty(infoRequest.getItemList())) {
                log.error("批量查询活动货品列表为空，参数：{}", infoRequest);
                throw new FacadeException("OTS-08-001-01-16-005");
            }
            /**
             * 校验原品数量
             */
            Long itemQuantity = infoRequest.getItemList().get(0).getItemQuantity();
            if (Objects.isNull(itemQuantity) || itemQuantity <= 0) {
                log.error("批量查询活动,原品数量为空，或者为0，参数：{}", infoRequest);
                throw new FacadeException("OTS-08-001-01-16-035");
            }

            /**
             * 活动使用时间	Y
             */
            if (Objects.isNull(infoRequest.getActivityUseTime())) {
                log.error("批量查询活动使用时间为空，参数：{}", infoRequest);
                throw new FacadeException("OTS-08-001-01-16-006");
            }

            /**
             * 交货时间，必填
             */
            if (Objects.isNull(infoRequest.getDeliveryDate())) {
                log.error("批量查询活动,交货时间为空，参数：{}", infoRequest);
                throw new FacadeException("OTS-08-001-01-16-007");
            }

            /**
             * 销售组织,必填
             */
            if (StringUtils.isBlank(infoRequest.getSalesOrganization())) {
                log.error("批量查询活动,销售组织为空，参数：{}", infoRequest);
                throw new FacadeException("OTS-08-001-01-16-008");
            }
        });
    }

}
